import { checkBlanks, checkReg, validate } from "./tools";
import $ from "jquery";
import { webPath } from "./config";

var _this;
/**
 * 初始化按钮
 */
function initToolBar(obj) {
    //按钮初始化
    _this = obj;
    let handler;
    if (_this.pageName == "MyFlow")
        handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    if (_this.pageName == "MyView")
        handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyView");
    if (_this.pageName == "MyCC")
        handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_CC");
    handler.AddJson(_this.params);
    let data = handler.DoMethodReturnString("InitToolBar"); //执行保存方法.
    if (data.indexOf("err@") != -1) {
        _this.$alert(data.replace('err@', ''), {
            dangerouslyUseHTMLString: true
        });
        return;
    }
    data = JSON.parse(data);
    _this.toolBtns = data.ToolBar == undefined ? data : data.ToolBar;
    _this.toNodes = data.ToNodes;
    if (data.WF_Node == undefined && _this.$parent.$parent.$parent)
        _this.node = _this.$parent.$parent.$parent.node;
    else
        _this.node = data.WF_Node[0];
}

function Save() {
    if (_this.$parent.$parent.$parent)
        _this.$parent.$parent.$parent.Save();
}
/**
 * 发送
 */
/**
 * 流程发送
 */
function Send(obj, isHuiQian) {
    _this = obj;
    _this.btnDisabled = true;
    _this.sendLoading = true;

    //不同的流程保存数据不同
    //嵌入式表单、SDK表单
    if (_this.node.FormType == 2 || _this.node.FormType == 3) {
        if (SendSelfFrom() == false)
            return;
    }
    //表单方案：傻瓜表单、自由表单、开发者表单、累加表单、绑定表单库的表单（单表单)
    if (_this.node.FormType == 0
        || _this.node.FormType == 1
        || _this.node.FormType == 10
        || _this.node.FormType == 11
        || _this.node.FormType == 12) {
        if (NodeFormSend() == false)
            return;
    }

    //绑定多表单
    if (_this.node.FormType == 5)
        if (FromTreeSend() == false)
            return;


    //必填项和正则表达式检查.
    if (checkBlanks() == false) {
        alert("检查必填项出现错误，边框变红颜色的是否填写完整？");
        _this.btnDisabled = false;
        _this.sendLoading = false;
        return false;
    }

    if (checkReg() == false) {
        alert("发送错误:请检查字段边框变红颜色的是否填写完整？");
        _this.btnDisabled = false;
        _this.sendLoading = false;
        return false;
    }
    //判断是否启用审核组件
    if (_this.node.FWCSta != 0) {
        if (_this.$parent.$parent.$parent && _this.$parent.$parent.$parent.WorkCheck_Save() == false) {
            _this.btnDisabled = false;
            _this.sendLoading = false;
            return false;
        }

    }

    //如果启用了流程流转自定义，必须设置选择的游离态节点
    if ($('[name=TransferCustom]').length > 0) {
        let ens = new this.Entities("BP.WF.TransferCustoms");
        ens.Retrieve("WorkID", _this.$route.params.WorkID, "IsEnable", 1);
        if (ens.length == 0) {
            _this.$alert("该节点启用了流程流转自定义，但是没有设置流程流转的方向，请点击流转自定义按钮进行设置");
            _this.btnDisabled = false;
            _this.sendLoading = false;
            return false;
        }
    }


    let toNodeID = 0;

    //含有发送节点 且接收
    if (_this.toNodes.length > 0) {
        toNodeID = _this.selectNode;
        //获取到达节点的信息
        let toNode;
        for (let i = 0; i < _this.toNodes.length; i++) {
            if (_this.toNodes[i].No == toNodeID) {
                toNode = _this.toNodes[i];
                break;
            }
        }

        if (toNode.IsSelectEmps == "1") { //跳到选择接收人窗口

            Save(); //执行保存.

            if (isHuiQian == true) {
                _this.dialogFormVisible = true;
                _this.judgeOperation = "HuiQian";
                _this.title = "选择会签人";


            } else {

                _this.dialogFormVisible = true;
                _this.judgeOperation = "sendAccepter";
                _this.title = "选择接收人";
                console.log('toNodeID--', toNodeID);
            }
            _this.btnDisabled = false;
            _this.sendLoading = false;
            return false;

        } else {

            if (isHuiQian == true) {

                Save(obj, 1); //执行保存.
                _this.dialogFormVisible = true;
                _this.judgeOperation = "HuiQian";
                _this.title = "选择会签人";
                _this.btnDisabled = false;
                _this.sendLoading = false;
                return false;
            }
        }
    }
    //执行发送.
    execSend(obj, toNodeID);
}

function execSend(obj, toNodeID) {
    _this = obj;
    //组织数据.
    let handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    /*if(_this.node.FormType != 3 && _this.node.FormType != 2){
        let dataStrs = getFormData(true, true,_this.$route.params) + "&ToNode=" + toNodeID;
        $.each(dataStrs.split("&"), function (i, o) {
            //计算出等号的INDEX
            let indexOfEqual = o.indexOf('=');
            let objectKey = o.substr(0, indexOfEqual);
            let objectValue = o.substr(indexOfEqual + 1);
            if (validate(objectValue)) {
                handler.AddPara(objectKey, objectValue);
            } else {
                handler.AddPara(objectKey, "");
            }
        });
    }*/

    handler.AddJson(_this.$store.getters.getData);
    let data = handler.DoMethodReturnString("Send"); //执行保存方法.

    if (data.indexOf('err@') == 0) { //发送时发生错误

        var reg = new RegExp('err@', "g")
        data = data.replace(reg, '');
        _this.$message({
            type: 'error',
            message: data
        });
        _this.btnDisabled = false;
        _this.sendLoading = false;
        return;
    }
    var url = "";
    if (data.indexOf('TurnUrl@') == 0) {  //发送成功时转到指定的URL
        url = data;
        url = url.replace('TurnUrl@', '');
        _this.params.IFrameSrc = url;
        _this.$store.commit('setData', params);
        _this.$route.push({ name: "IFrameComponent" });
        return;
    }

    if (data.indexOf('SelectNodeUrl@') == 0) {
        _this.dialogFormVisible = true;
        _this.judgeOperation = "SelectNodeUrl";
        _this.btnDisabled = false;
        _this.sendLoading = false;
        return;
    }



    if (data.indexOf('url@') == 0) {  //发送成功时转到指定的URL

        if (data.indexOf('Accepter') != 0 && data.indexOf('AccepterGener') == -1) {

            //求出来 url里面的FK_Node=xxxx
            var params = data.split("&");
            for (var i = 0; i < params.length; i++) {
                if (params[i].indexOf("ToNode") == -1)
                    continue;

                toNodeID = params[i].split("=")[1];
                break;
            }
            _this.dialogFormVisible = true;
            _this.judgeOperation = "sendAccepter";
            params = _this.$store.getters.getData;
            params.ToNode = toNodeID;
            _this.$store.commit('setData', params);
            _this.btnDisabled = false;
            _this.sendLoading = false;
            return;
        }
    }
    OptSuc(data, _this);
}

//发送 退回 移交等执行成功后转到  指定页面
function OptSuc(msg, _this) {
    if ($('#returnWorkModal:hidden').length == 0 && $('#returnWorkModal').length > 0) {
        $('#returnWorkModal').modal().hide()
    }
    msg = msg.replace("@查看<img src='/WF/Img/Btn/PrintWorkRpt.gif' >", '')

    msg = msg.replace(/@/g, '<br/>').replace(/null/g, '');
    _this.$alert(msg, '发送成功', {
        dangerouslyUseHTMLString: true
    });
    _this.$router.push({
        name: "todolist"
    });
    return;
}

/**
 * 节点表单发送前的验证
 */
function NodeFormSend() {

    //保存从表信息待定
    //保存附件待定
    //审核组件
    //判断是否启用审核组件
    if (_this.node.FWCSta != 0) {
        if (_this.$parent.$parent.$parent && _this.$parent.$parent.$parent.WorkCheck_Save() == false) {
            _this.btnDisabled = false;
            _this.sendLoading = false;
            return false;
        }

    }
    //必填项和正则表达式检查.
    if (checkBlanks() == false) {
        alert("检查必填项出现错误，边框变红颜色的是否填写完整？");
        return false;
    }

    if (checkReg() == false) {
        alert("发送错误:请检查字段边框变红颜色的是否填写完整？");
        return false;
    }

    //如果启用了流程流转自定义，必须设置选择的游离态节点
    if ($('[name=TransferCustom]').length > 0) {
        var ens = new _this.Entities("BP.WF.TransferCustoms");
        ens.Retrieve("WorkID", _this.params.WorkID, "IsEnable", 1);
        if (ens.length == 0) {
            alert("该节点启用了流程流转自定义，但是没有设置流程流转的方向，请点击流转自定义按钮进行设置");
            return false;
        }
    }
    return true;
}
/**
 * 绑定多表单发送前的验证
 */
function FromTreeSend() {
    return true;
}
/**
 * 嵌入式表单
 */
function SendSelfFrom() {
    let val = _this.$parent.$parent.$parent.Save();
    if (val == false) {
        return false;
    }
    if (val != true) {
        //就说明是传来的参数，这些参数需要存储到WF_GenerWorkFlow里面去，用于方向条件的判断。
        let handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
        handler.AddPara("WorkID", _this.params.WorkID);
        handler.AddPara("Paras", val);
        handler.DoMethodReturnString("SaveParas");
    }
    return true;
}

/**
 * 帮助提示
 * @param {启用规则} helpRole
 * @param {节点ID} FK_Node
 */
function HelpOper(helpRole, FK_Node, _this) {
    //判断该节点是否启用了帮助提示 0 禁用 1 启用 2 强制提示 3 选择性提示
    if (helpRole != 0) {
        var count = 0;
        var mypk = _this.webUser.No + "_ND" + FK_Node + "_HelpAlert";
        var userRegedit = new this.Entity("BP.Sys.UserRegedit");
        userRegedit.SetPKVal(mypk);
        count = userRegedit.RetrieveFromDBSources();
        if (helpRole == 2 || (count == 0 && helpRole == 3)) {
            var filename = webPath + "/DataUser/CCForm/HelpAlert/" + FK_Node + ".htm";
            var htmlobj = $.ajax({ url: filename, async: false });
            if (htmlobj.status == 404)
                return;
            var str = htmlobj.responseText;
            if (str != null && str != "" && str != undefined) {
                _this.$alert(str, '帮助指引', {
                    dangerouslyUseHTMLString: true,
                    beforeClose: (action, instance, done) => {
                        if (count == 0) {
                            //保存数据
                            userRegedit.FK_Emp = _this.webUser.No;
                            userRegedit.FK_MapData = "ND" + FK_Node;
                            userRegedit.Insert();

                        }
                        done();
                    }

                });
            }
        }
    }
}


export {
    initToolBar, //初始化按钮
    Send, //发送操作
    HelpOper,//帮助提示
}